<?php
/// O'My Friends: Personal Social Network Graph on Facebook
/// author : Minkyu Shim (minkyu.shim@gmail.com

function fetchAndProcessData($flag, &$friends, &$error, $fetchFunc, $processFunc){
    
    $data = null;
    
    //check cache
//    if(isset($_SESSION["mode_".$flag])){
//        $data = $_SESSION["mode_".$flag];
//    }else{
        //if there is no data in cache, fetch from server
        try{
            //fetch from server
        	$data = call_user_func($fetchFunc);

            //store data into cache
            $_SESSION["mode_".$flag] = $data;
        }catch(Exception $e){
            //set error bit
            $error += $flag;
        }
//    }
    if(($error & $flag) !== $flag){
        call_user_func($processFunc, &$friends, $data);

    }
    
}

//For uasort
function cmp($a, $b){
    $as = $a->getNumberOfAllCommunications();
    $bs = $b->getNumberOfAllCommunications();
    if($as == $bs){
        return 0;
    }
    return ($as > $bs) ? -1 : 1;
}

function compareTime($a, $b){
    $aTime = $a->time;
    $bTime = $b->time;
    if($aTime == $bTime){
        return 0;
    }
    return ($aTime > $bTime) ? -1 : 1;
}

//For Debug
function trace($obj){
	print('<pre>');
	print_r($obj);
	print('</pre>');
}

function refresh(){
    $page = $_SERVER['PHP_SELF'];
    header("Refresh: 0; url=$page");
}

function callFb($url, $params)
{
	$ch = curl_init();
	curl_setopt_array($ch, array(
		CURLOPT_URL => $url,
		CURLOPT_POSTFIELDS => http_build_query($params),
		CURLOPT_RETURNTRANSFER => true,
		CURLOPT_VERBOSE => true,
		CURLOPT_CAINFO => dirname(__FILE__) . '/fb_ca_chain_bundle.crt'
	));

	$result = curl_exec($ch);
	curl_close($ch);
	return $result;
}

//Generate a valid signed_request
function generateSignedRequest($session){
    
    //Create payload
    //  create valid object
    $session['algorithm'] = 'HMAC-SHA256';

    //  json_encode and facebook base64 encoding
    $payload = base64_encode(strtr(json_encode($session), '+/', '-_'));

    //Create sig
    $sig = hash_hmac('sha256', $payload, FB_APP_SECRET, $raw = true);;
    
    //    Facebook Base64 Encoding
    $encoded_sig = base64_encode(strtr($sig, '+/', '-_'));
    
    $signed_request = $encoded_sig.".".$payload;

    return $signed_request;
}

//From facebook php-sdk
function parse_signed_request($signed_request, $secret) {
  list($encoded_sig, $payload) = explode('.', $signed_request, 2); 

  // decode the data
  $sig = base64_url_decode($encoded_sig);
  $data = json_decode(base64_url_decode($payload), true);
  
  if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
    error_log('Unknown algorithm. Expected HMAC-SHA256');
    return null;
  }

  // check sig
  $expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true);
  if ($sig !== $expected_sig) {
    error_log('Bad Signed JSON signature!');
    return null;
  }

  return $data;
}

//From facebook php-sdk
function base64_url_decode($input) {
  return base64_decode(strtr($input, '-_', '+/'));
}

function writeToLogfile($msg){
	try{
		file_put_contents("../log/report_".date('Y_m_d').".txt", $msg, FILE_APPEND); 
	}catch(Exception $e){
		error_log($e->getMessage());
	}
}
